"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _react = _interopRequireWildcard(require("react"));

var _classnames = _interopRequireDefault(require("classnames"));

var _configContext = require("../../../../extends/configContext");

var _isMobile = _interopRequireDefault(require("../../../../utils/is-mobile"));

var _controllerItem = _interopRequireDefault(require("./controller-item"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

var WebImgPreviewerController = function WebImgPreviewerController(_ref) {
  var _ref$imgUrls = _ref.imgUrls,
      imgUrls = _ref$imgUrls === void 0 ? [] : _ref$imgUrls,
      _ref$currentImgIdx = _ref.currentImgIdx,
      currentImgIdx = _ref$currentImgIdx === void 0 ? 0 : _ref$currentImgIdx,
      _ref$visible = _ref.visible,
      visible = _ref$visible === void 0 ? false : _ref$visible,
      _ref$onImgClick = _ref.onImgClick,
      onImgClick = _ref$onImgClick === void 0 ? function () {} : _ref$onImgClick,
      _ref$onError = _ref.onError,
      onError = _ref$onError === void 0 ? function (i) {
    return '';
  } : _ref$onError;

  var _useConfig = (0, _configContext.useConfig)(),
      clsPrefix = _useConfig.clsPrefix;

  var _useState = (0, _react.useState)(0),
      _useState2 = _slicedToArray(_useState, 2),
      translateX = _useState2[0],
      setTranslateX = _useState2[1];

  var _useState3 = (0, _react.useState)(false),
      _useState4 = _slicedToArray(_useState3, 2),
      isVisible = _useState4[0],
      setIsVisible = _useState4[1];

  var timerRef = _react.default.useRef(null);

  var controllerRef = _react.default.useRef(null);

  var controllerLock = _react.default.useRef(null); // 记录当前滑动位置，用来计算下一帧的位置


  var currentX = _react.default.useRef(null);

  var IS_MOBILE = false;

  if (typeof window !== 'undefined') {
    IS_MOBILE = (0, _isMobile.default)();
  }

  (0, _react.useEffect)(function () {
    var mouseMoveEventHandler = function mouseMoveEventHandler() {
      if (controllerLock.current) return;
      setIsVisible(true);

      if (timerRef.current) {
        clearTimeout(timerRef.current);
      }

      timerRef.current = setTimeout(function () {
        setIsVisible(false);
      }, 2000);
    };

    var mouseEnterControllerHandler = function mouseEnterControllerHandler() {
      setIsVisible(true);
      controllerLock.current = true;

      if (typeof window !== 'undefined') {
        document.removeEventListener('mousemove', mouseMoveEventHandler);
      }

      if (timerRef.current) {
        clearTimeout(timerRef.current);
      }
    };

    var mouseOutControllerHandler = function mouseOutControllerHandler() {
      controllerLock.current = null;

      if (typeof window !== 'undefined') {
        document.addEventListener('mousemove', mouseMoveEventHandler, false);
      }
    };

    if (typeof window !== 'undefined') {
      document.addEventListener('mousemove', mouseMoveEventHandler, false);
    }

    if (controllerRef.current) {
      if (!IS_MOBILE) {
        controllerRef.current.addEventListener('mouseover', mouseEnterControllerHandler, false);
        controllerRef.current.addEventListener('mouseleave', mouseOutControllerHandler, false);
      }
    }

    return function () {
      if (typeof window !== 'undefined') {
        document.removeEventListener('mousemove', mouseMoveEventHandler);
      }

      if (controllerRef.current) {
        controllerRef.current.removeEventListener('mouseover', mouseEnterControllerHandler);
        controllerRef.current.removeEventListener('mouseleave', mouseOutControllerHandler);
      }
    };
  }, []);
  (0, _react.useEffect)(function () {
    // ssr 不执行
    setTimeout(function () {
      if (typeof window !== 'undefined') {
        var container = controllerRef.current;

        if (container) {
          var elements = document.getElementsByClassName("".concat(clsPrefix, "-img-previewer__controller-item"));
          var containerWidth = container.getBoundingClientRect().width;
          var offset = Array.from(elements).slice(0, currentImgIdx).reduce(function (prev, curr) {
            return prev + curr.getBoundingClientRect().width;
          }, 0);

          if (offset >= containerWidth / 2) {
            if (offset < containerWidth - 40) {
              // 修正 40px
              setTranslateX(offset - containerWidth / 2 + 40);
            } else {
              setTranslateX(offset - containerWidth / 2 + 30);
            }
          } else {
            setTranslateX(0);
          }
        }
      }
    }, 300);
  }, [currentImgIdx]);
  return /*#__PURE__*/_react.default.createElement("div", {
    ref: controllerRef,
    className: (0, _classnames.default)("".concat(clsPrefix, "-img-previewer__controller-wrapper"), {
      'is-mobile': IS_MOBILE
    }),
    style: {
      visibility: isVisible || IS_MOBILE ? 'visible' : 'hidden',
      overflow: 'hidden'
    },
    onTouchStart: function onTouchStart(e) {
      e.stopPropagation();
      currentX.current = e.touches[0].clientX;
    },
    onTouchMove: function onTouchMove(e) {
      e.stopPropagation();
      var touchDeltaX = e.touches[0].clientX - currentX.current;
      currentX.current = e.touches[0].clientX;
      var container = controllerRef.current;
      var containerWidth = container.getBoundingClientRect().width;
      var elements = document.getElementsByClassName("".concat(clsPrefix, "-img-previewer__controller-item"));
      var offset = Array.from(elements).slice(0, elements.length - 1).reduce(function (prev, curr) {
        return prev + curr.getBoundingClientRect().width;
      }, 0);
      setTranslateX(function (currentTranslateX) {
        if (currentTranslateX - touchDeltaX <= 0) {
          return 0;
        }

        if (currentTranslateX - touchDeltaX >= offset - containerWidth / 2 + 30) {
          return offset - containerWidth / 2 + 30;
        }

        return currentTranslateX - touchDeltaX;
      });
    },
    onClick: function onClick(e) {
      e.stopPropagation();
      e.preventDefault();
    }
  }, /*#__PURE__*/_react.default.createElement("div", {
    style: {
      transform: "translateX(-".concat(translateX, "px)"),
      transition: 'transform .3s'
    },
    className: (0, _classnames.default)("".concat(clsPrefix, "-img-previewer__controller-container"))
  }, imgUrls.map(function (imgSrc, idx) {
    return /*#__PURE__*/_react.default.createElement(_controllerItem.default, {
      className: (0, _classnames.default)("".concat(clsPrefix, "-img-previewer__controller-item"), {
        'is-active': idx === currentImgIdx,
        'is-mobile': IS_MOBILE
      }),
      alt: '',
      isActive: idx === currentImgIdx,
      onClick: function onClick() {
        onImgClick(idx);
      },
      idx: idx,
      onError: onError,
      src: imgSrc
    });
  })));
};

var _default = WebImgPreviewerController;
exports.default = _default;